//
//  M_HuodongArticleVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/9.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import WebKit
import SDWebImage

class M_HuodongArticleVC: BaseViewControllerWithHeader,WKUIDelegate,WKNavigationDelegate {
    lazy var backBtn : Button = {
        let v = self.drawRightButton(title: "返回")
        v.addTarget(self, action: #selector(fanhuiClick(btn:)), for: .touchUpInside)
        return v
    }()
    let webView = WKWebView()
    var webViewTitle = ""
    var artId = "" {
        didSet {
            if artId.count > 0 {
                loadUrl(ARTICLE_URL + artId)
                queryArticleInfo(id: artId)
            }
        }
    }
    var curUrl = ""
    var dataDic : [String:Any?]? = nil
    
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .clear
        webView.drawView(view: v) { (make) in
            make.left.top.equalToSuperview()
            make.height.width.equalToSuperview()
        }
        let img = v.drawImage(named: "zhaobudaoyemian_114") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-80)
            make.height.width.equalTo(200)
        }
        img.contentMode = .scaleAspectFit
        
        v.drawLabel(text: "找不到页面", fontSize: 19, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }.textAlignment = .center
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        
        
        //禁止长按,放缩
        var javascript = "document.documentElement.style.webkitTouchCallout='none';"//禁止长按
        javascript += "document.documentElement.style.webkitUserSelect='none';"//禁止选择
        var noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        webView.configuration.userContentController.addUserScript(noneSelectScript)
        javascript = "var script = document.createElement('meta');script.name = 'viewport';script.content=\"width=device-width, user-scalable=no\";document.getElementsByTagName('head')[0].appendChild(script);"//禁止缩放
        noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        webView.configuration.userContentController.addUserScript(noneSelectScript)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    // 进度条
    lazy var progressView:UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = UIColor.orange
        progress.trackTintColor = .clear
        return progress
    }()
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
            if keyPath == "estimatedProgress"{
                progressView.alpha = 1.0
                progressView.setProgress(Float((self.webView.estimatedProgress)), animated: true)
                if (self.webView.estimatedProgress)  >= 1.0 {
                    UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                        self.progressView.alpha = 0
                    }, completion: { (finish) in
                        self.progressView.setProgress(0.0, animated: false)
                    })
                }
            }
             else if keyPath == "title" {
                 webViewTitle = webView.title ?? ""
            }
        }
}

// MARK:- UI
extension M_HuodongArticleVC {
    func setupUI() {
//        headTitle.text = "活动推文"
        
        safeView.drawView(view: webView) { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        webView.uiDelegate = self
        webView.navigationDelegate = self
        self.webView.addObserver(self, forKeyPath: "title", options: .old, context: nil)
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .old, context: nil)
        
        headView.drawView(view: progressView) { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(2)
        }
        
        drawRightButton(imageName: "fenxiang_90")
        .addTarget(self, action: #selector(_fenxiangButtonClick(button:)), for: .touchUpInside)
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

    }
}

//获取文章信息（主要是为了获取分享图片）
extension M_HuodongArticleVC {
    func queryArticleInfo(id:String){
        API.formRequest(url: .A_getSysarticleById , params: ["id" : id]) { (result) in
            if result.success {
                if self.dataDic == nil {
                    self.dataDic = result.data?.getDictionary("data")
                    let urlAry = self.dataDic?.getString("imgs")?.components(separatedBy: ",") ?? [""]
                    if let url = urlAry.safeGet(idx: 0) {
                        if SDImageCache.shared.imageFromCache(forKey:url) == nil {
                            let urlimg = URL(string: url)
                            let downloader = SDWebImageDownloader.shared
                            downloader.downloadImage(with: urlimg, options: [], progress: nil, completed: { (image,data,error,sec) in
                                SDImageCache.shared.store(image, forKey: url, completion: nil)
                            })
                        }
                    }
                }
            }
        }
    }
}

// MARK:- 事件
extension M_HuodongArticleVC {
    @objc func fanhuiClick(btn: Button) {
        popViewController()
    }
    
    func loadUrl(_ url : String) {
        curUrl = url
        let mapwayURL = URL(string: curUrl)!
        let mapwayRequest = URLRequest(url: mapwayURL)
        webView.load(mapwayRequest)
    }
    
    func loadString(_ htmlString : String) {
        webView.loadHTMLString(htmlString, baseURL: nil)
    }
    
    ///WKUIDelegate,WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
        print("url:\(String(describing: url)), host:\(String(describing: url?.host)), path:\(String(describing: url?.path)), query:\(String(describing: url?.query))")
        if let query = url?.query?.urlqueryToDictionary() {
            print("截取的参数:" + query.jsonString)
            if query.getString("action") == "commoditvDetails",let productNo = query.getString("productID") {
                let vc = M_ProductDetailVC(info: ["productNo":productNo])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "slideshowSub",let id = query.getString("special") {
                let vc = M_ArticleVC()
                pushViewController(vc)
                let url = SPLICE_URL + id
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "slideshowSub",let id = query.getString("id"),let _ = query.getString("division") {
                let vc = M_ProductDetailVC(info: ["productNo":id])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "special",let id = query.getString("id"),let division = query.getString("division") {
                let ary = [["cataID":id, "cataName":""]]
                let vc = M_ProductByCategoryVC(dataSubArr: ary, curDicIndex: 0,zoneCode: .init(fromDictionary: ["code":division,"name":"","sort":0]))
                pushViewController(vc)
                vc.tabHeaderHide = true
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "party",let id = query.getString("article") {
                let vc = M_ArticleVC()
                pushViewController(vc)
                vc.headTitle.text = "活动推文"
                vc.artId = "\(id)"
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "party",query.getString("more") == "more" {
                let noT = NSNotification.Name(rawValue: GOTOHONME)
                let dic = ["selIndex":2]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "special",let id = query.getString("special") {
                let vc = M_ArticleVC()
                pushViewController(vc)
                let url = SPLICE_URL + id
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            } else if query.getString("action") == "autotrophy",let id = query.getString("special") {
                let vc = M_ArticleVC()
                pushViewController(vc)
                let url = SPLICE_URL + id
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "autotrophy",let productNo = query.getString("productNo") {
                let vc = M_ProductDetailVC(info: ["productNo":productNo])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "jingdong",let productNo = query.getString("goodsID") {
                let vc = M_ProductDetailVC(info: ["productNo":productNo])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "jingdong",let id = query.getString("special") {
                let vc = M_ArticleVC()
                pushViewController(vc)
                let url = SPLICE_URL + id
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "jingdong",let productNo = query.getString("productNo") {
                let vc = M_ProductDetailVC(info: ["productNo":productNo])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "addToshopingCart",let productNo = query.getString("productNo") {
                addCar(productNo: productNo)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "main" {
                decisionHandler(.allow)
                return
            }
            else if query.getString("action") == "Advertisement", let special = query.getString("special")  {
                let vc = M_ArticleVC()
                pushViewController(vc)
                let url = SPLICE_URL + special
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "Advertisement", let url = query.getString("url")  {
                let vc = M_ArticleVC()
                pushViewController(vc)
                vc.loadUrl(url)
                decisionHandler(.cancel)
                return
            }
            else if query.getString("action") == "recommend", let productNo = query.getString("productNo")  {
                let vc = M_ProductDetailVC(info: ["productNo":productNo])
                pushViewController(vc)
                decisionHandler(.cancel)
                return
            }
        }
        if navigationAction.navigationType == .linkActivated {
            let mapwayURL = URL(string: curUrl)!
            let mapwayRequest = URLRequest(url: url ?? mapwayURL)
            webView.load(mapwayRequest)
            curUrl = url?.absoluteString ?? ""
            decisionHandler(.cancel)
        }
        else {
            curUrl = url?.absoluteString ?? ""
            decisionHandler(.allow)
        }
    }
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        defultView.isHidden = true
    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
    }
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        self.title = self.webView.title
        MBProgressHUD.hideOrDecrease()
    }
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        /// 弹出提示框点击确定返回
//        let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
//        let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
//            _=self.navigationController?.popViewController(animated: true)
//        }
//        alertView.addAction(okAction)
//        self.present(alertView, animated: true, completion: nil)
        
        MBProgressHUD.hideOrDecrease()
        defultView.isHidden = false
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        MBProgressHUD.hideOrDecrease()
        defultView.isHidden = false
    }
    
    @objc func _fenxiangButtonClick(button: Button) {
        UMSocialUIManager.setPreDefinePlatforms([NSNumber.init(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue), NSNumber.init(value: UMSocialPlatformType.wechatSession.rawValue)])
        UMSocialUIManager.addCustomPlatformWithoutFilted(UMSocialPlatformType(rawValue: 1001)!, withPlatformIcon: UIImage.init(named: "share_link"), withPlatformName: "复制链接")
        UMSocialUIManager.showShareMenuViewInWindow { (platform: UMSocialPlatformType, userInfo: [AnyHashable : Any]?) in
            if platform == UMSocialPlatformType(rawValue: 1001)! {
                let pastboard = UIPasteboard.general
                pastboard.string = self.curUrl

                let popup = PopupBox(infoText: "已复制")
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return
            }
            
            let messageObject = UMSocialMessageObject()
            let urlAry = self.dataDic?.getString("imgs")?.components(separatedBy: ",") ?? [""]
            let img =  SDImageCache.shared.imageFromCache(forKey:urlAry[0]) ?? UIImage(named: "share_link2")
            let webMessageContent = UMShareWebpageObject.shareObject(withTitle: self.dataDic?.getString("title") ?? self.webViewTitle, descr: self.dataDic?.getString("enterpriseName"), thumImage: img)

            webMessageContent?.webpageUrl = self.curUrl

            messageObject.shareObject = webMessageContent
            UMSocialManager.default()?.share(to: platform, messageObject: messageObject, currentViewController: self, completion: { (info, error) in
                
            })
        }
    }
    
    @objc func _gouwucheButtonClick(button: Button) {
        let vc = M_CartListVC()
        vc.isshowBack = true
        pushViewController(vc)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    
    @objc func onSearchAction(button:UIButton){
        let vc = M_SearchPageVC()
        pushViewController(vc)
    }
    
    func addCar(productNo: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_AddCart, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "成功加入购物车")
                popup.show(vc: UIViewController.topMostController() ?? self)

                let noT = NSNotification.Name(rawValue: CAR_CHANGE)
                let dic = ["key":"value"]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "加入购物车失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
}
